<template>
  <div class="outgoing-invoices-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" label-width="80px" inline>
        <el-form-item label="发票号码">
          <el-input v-model="filterForm.invoiceNumber" placeholder="请输入发票号码" />
        </el-form-item>
        <el-form-item label="销方名称">
          <el-input v-model="filterForm.sellerName" placeholder="请输入销方名称" />
        </el-form-item>
        <el-form-item label="购方名称">
          <el-input v-model="filterForm.buyerName" placeholder="请输入购方名称" />
        </el-form-item>
        <el-form-item label="开票日期">
          <el-date-picker
            v-model="filterForm.invoiceDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 发票列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="list-header">
          <div class="header-title">
            <span>销项发票列表</span>
            <el-tooltip content="跳转到税务局全量发票查询页面" placement="top">
              <el-link 
                href="https://dppt.zhejiang.chinatax.gov.cn:8443/invoice-query/invoice-query" 
                target="_blank" 
                type="primary" 
                :underline="false"
                class="external-link"
              >
                <el-icon><Position /></el-icon>
                税务局查询
              </el-link>
            </el-tooltip>
          </div>
          <div class="list-actions">
            <el-button type="primary" @click="handleAdd">新增</el-button>
            <el-button @click="handleImport">导入</el-button>
            <el-button @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="invoiceList"
        v-loading="loading"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="invoiceNumber" label="发票号码" min-width="120" />
        <el-table-column prop="invoiceCode" label="发票代码" min-width="100" />
        <el-table-column prop="sellerName" label="销方名称" min-width="150" />
        <el-table-column prop="buyerName" label="购方名称" min-width="150" />
        <el-table-column prop="totalAmount" label="金额" min-width="100" align="right">
          <template #default="{ row }">
            ¥{{ formatAmount(row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="taxAmount" label="税额" min-width="100" align="right">
          <template #default="{ row }">
            ¥{{ formatAmount(row.taxAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalTaxAmount" label="价税合计" min-width="120" align="right">
          <template #default="{ row }">
            ¥{{ formatAmount(row.totalTaxAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="invoiceDate" label="开票日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.invoiceDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看/编辑发票抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      direction="rtl"
      size="50%"
      @close="handleDrawerClose"
    >
      <OutgoingInvoiceEdit 
        v-if="drawerVisible" 
        :operation="currentOperation"
        :invoice-id="currentInvoiceId"
        @save-success="handleSaveSuccess"
        @cancel="handleDrawerClose"
      />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOutgoingInvoices, deleteOutgoingInvoice, importOutgoingInvoices, exportOutgoingInvoices } from '@/api/invoice'
import OutgoingInvoiceEdit from './OutgoingInvoiceEdit.vue'
import { Position } from '@element-plus/icons-vue'

// 路由
const router = useRouter()

// 加载状态
const loading = ref(false)

// 抽屉状态
const drawerVisible = ref(false)
const currentOperation = ref<'view' | 'edit'>('view')
const currentInvoiceId = ref<string | number | undefined>(undefined)

// 筛选表单
const filterForm = reactive({
  invoiceNumber: '',
  sellerName: '',
  buyerName: '',
  invoiceDateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 发票列表
const invoiceList = ref<any[]>([])

// 选中的发票
const selectedInvoices = ref<any[]>([])

// 抽屉标题
const drawerTitle = computed(() => {
  if (!currentInvoiceId.value) {
    return '新增销项发票'
  }
  switch (currentOperation.value) {
    case 'view': return '查看销项发票'
    case 'edit': return '编辑销项发票'
    default: return '销项发票'
  }
})

// 获取状态类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'normal': return 'success'
    case 'void': return 'danger'
    case 'draft': return 'warning'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'normal': return '正常'
    case 'void': return '已作废'
    case 'draft': return '草稿'
    default: return '未知'
  }
}

// 格式化金额
const formatAmount = (amount: string | number) => {
  const num = typeof amount === 'string' ? parseFloat(amount) : amount;
  return num ? num.toFixed(2) : '0.00'
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getInvoiceList()
}

// 重置
const handleReset = () => {
  filterForm.invoiceNumber = ''
  filterForm.sellerName = ''
  filterForm.buyerName = ''
  filterForm.invoiceDateRange = []
  pagination.currentPage = 1
  getInvoiceList()
}

// 新增
const handleAdd = () => {
  currentOperation.value = 'edit' // 使用edit模式来新增
  currentInvoiceId.value = undefined // 没有ID表示新增
  drawerVisible.value = true
}

// 导入
const handleImport = () => {
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.xlsx,.xls,.csv'
  input.onchange = async (event: any) => {
    const file = event.target.files[0]
    if (!file) return
    
    try {
      await importOutgoingInvoices(file)
      ElMessage.success('导入成功')
      getInvoiceList() // 刷新列表
    } catch (error: any) {
      ElMessage.error('导入失败: ' + (error.message || '未知错误'))
    }
  }
  input.click()
}

// 导出
const handleExport = async () => {
  try {
    // 构建查询参数
    const query = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      invoiceNumber: filterForm.invoiceNumber,
      sellerName: filterForm.sellerName,
      buyerName: filterForm.buyerName,
      startDate: filterForm.invoiceDateRange && filterForm.invoiceDateRange.length === 2 ? filterForm.invoiceDateRange[0] : undefined,
      endDate: filterForm.invoiceDateRange && filterForm.invoiceDateRange.length === 2 ? filterForm.invoiceDateRange[1] : undefined
    }
    
    const blob = await exportOutgoingInvoices(query)
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `销项发票_${new Date().toISOString().slice(0, 10)}.xlsx`
    link.click()
    
    // 清理
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (error: any) {
    ElMessage.error('导出失败: ' + (error.message || '未知错误'))
  }
}

// 查看
const handleView = (row: any) => {
  currentOperation.value = 'view'
  currentInvoiceId.value = row.id
  drawerVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  currentOperation.value = 'edit'
  currentInvoiceId.value = row.id
  drawerVisible.value = true
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除发票号码为 ${row.invoiceNumber} 的销项发票吗？`,
    '删除确认',
    {
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 执行删除操作
      await deleteOutgoingInvoice(row.id)
      ElMessage.success('删除成功')
      getInvoiceList()
    } catch (error: any) {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
    }
  }).catch(() => {
    // 取消删除
  })
}

// 选中项变化
const handleSelectionChange = (selection: any[]) => {
  selectedInvoices.value = selection
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getInvoiceList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  getInvoiceList()
}

// 获取发票列表
const getInvoiceList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const query = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      invoiceNumber: filterForm.invoiceNumber,
      sellerName: filterForm.sellerName,
      buyerName: filterForm.buyerName,
      startDate: filterForm.invoiceDateRange && filterForm.invoiceDateRange.length === 2 ? filterForm.invoiceDateRange[0] : undefined,
      endDate: filterForm.invoiceDateRange && filterForm.invoiceDateRange.length === 2 ? filterForm.invoiceDateRange[1] : undefined,
      sortField: 'invoice_date',
      sortOrder: 'desc'
    }
    
    // 调用后端API获取发票列表
    const data = await getOutgoingInvoices(query)
    invoiceList.value = data.items || []
    pagination.total = data.total || 0
  } catch (error: any) {
    ElMessage.error('获取发票列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 处理抽屉关闭
const handleDrawerClose = () => {
  drawerVisible.value = false
  currentInvoiceId.value = undefined
}

// 处理保存成功
const handleSaveSuccess = () => {
  handleDrawerClose()
  getInvoiceList() // 刷新列表
}

// 组件挂载时获取数据
onMounted(() => {
  getInvoiceList()
})
</script>

<style scoped>
.outgoing-invoices-container {
  padding: 20px 0;
}

.filter-card {
  margin-bottom: 20px;
}

.list-card {
  min-height: calc(100vh - 240px);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.external-link {
  font-size: 14px;
}

.list-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.invoice-preview {
  max-height: 60vh;
  overflow-y: auto;
}
</style>